package com.markhsiu.minimq.remote.transport.netty;

import com.markhsiu.minimq.message.Message;
import com.markhsiu.minimq.serialize.SerializeCodec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

 
public class MessageObjectEncoder extends MessageToByteEncoder<Message> {

    private SerializeCodec<Message> codec = null;

    public MessageObjectEncoder(final SerializeCodec<Message> codec) {
        this.codec = codec;
    }

    protected void encode(final ChannelHandlerContext ctx, final Message msg, final ByteBuf out) throws Exception {
    	byte[] data = codec.serialize(msg);
    	int dataLength = data.length;
        out.writeInt(dataLength);
        out.writeBytes(data);
    }
}
